# -*- coding: utf-8 -*-
import hashlib
import json
import random
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils import tz
from common.utils.exceptions import ParamError, KspayError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://mpay.9127pay.com/sspay/create.jsp?time={}&sign={}'

APP_CONF = {
    'KS': {
        # 'API_KEY': '038a95f0-e791-c03f-7347-4be423a381c5'
        'API_KEY': '34507596-0fc5-a33a-3a3f-ff65c8d5a208'
    },
    'BSCP': {
        'API_KEY': '5fb1b50f-8439-d574-1306-6312c08c3df7'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(p_data, ts, key):
    '''  生成下单签名 '''
    s = '{}{}{}'.format(p_data, ts, key)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().lower()
    _LOGGER.info(u'ks2pay origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, json, key):
    sign = params['sign']
    params.pop('sign')
    s = '{}{}{}'.format(json, params['time'], key)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    calculated_sign = m.hexdigest().lower()
    if sign != calculated_sign:
        _LOGGER.info("ks2pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


# 支付类型 [ wxpay, qqpay, alipay, unionpay jdpay ]
def _get_pay_type(type):
    if type == 'qq':
        return 'qqpay'
    elif type == 'alipay':
        return 'alipay'
    elif type == 'wxpay':
        return 'wxpay'
    elif type == 'jd':
        return 'jdpay'
    else:
        return 'unionpay'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("order_id", str(pay.id)),
        ('notify_url', '{}/pay/api/{}/ks2pay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ("payment", _get_pay_type(service)),
        ("bill_price", '%.2f' % pay_amount),
        ("info", {
            "device_ip": user_info.get('device_ip') or '171.212.112.44',
            "device_id": user_info.get('device_id') or 'IMEI00000001111112222222',
            "device_type": user_info.get('device_type') or 'android',
            "name": user_info.get('user_name') or '',
            "alipay_name": user_info.get('user_alicount') or '',
            "tel": user_info.get('tel') or '',
            "user_id": user_info.get('user_id') or '',
            "user_value": '100'
        })
    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, ts, api_key)
    headers = {'Content-type': 'application/json'}
    gate_url = _GATEWAY.format(ts, sign)
    _LOGGER.info('ks2pay brefore data: %s', p_data)
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=3)
    _LOGGER.info('ks2pay rsp data: %s\n%s', gate_url, response.text)
    res_obj = json.loads(response.text)
    url = res_obj['qrcode']
    if 'https://qr.alipay.com/' in url:
        _LOGGER.info('ks2pay_qr_alipay_com')
        raise KspayError('ks2pay url qr_alipay_com')
    return {'charge_info': url}


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("ks2pay notify data: %s", data)
    _LOGGER.info("ks2pay notify body: %s", request.body)
    verify_notify_sign(data, request.body, api_key)
    data = json.loads(request.body)
    pay_id = data['merchant_order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('ks2pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data.get('flashid')
    total_fee = float(data['payed_money'])

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
        'discount': discount,
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 10000:
        _LOGGER.info('ks2pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass


if __name__ == '__main__':
    # r = requests.get('http://gateway.ybbanggo.com/gateway/api/jumpPay/e000d11720d24bb299e58eb4c7c677b0', allow_redirects=False)
    # r = requests.get('http://pay.beehood.com/pay/yunruipay.jsp?prepareid=201805111750471011pLPnQG')
    # r = requests.get('http://pay.echongbei.com/AliPayH5.aspx?token=3193854')
    r = requests.get(
        'https://www.9q7o.cn:9099/gateway?ver=2.0\u0026action=quickpayment\u0026uid=800041\u0026outtradeno=DA2018051118075949424206246438\u0026fee=2000\u0026channel=1013\u0026returnUrl=https//:www.baidu.com\u0026selectUrl=https://cbpay2.9127pay.com/diaodepibao/channel_response/alipay/qinlingpay/qinling_ali\u0026attach=DA2018051118075949424206246438\u0026attachCode=DA2018051118075949424206246438\u0026ordername=DA2018051118075949424206246438\u0026sign=f2dfc20dff2f9526df806f54afedaa4f')
    # r = requests.get('http://api.bnvpay.cn/waporder/order_add?mch=816650352650\u0026pay_type=aliwap\u0026money=2000\u0026time=1526032454\u0026order_id=DA2018051117541419432606243212\u0026return_url=http%3A%2F%2Fwww.baidu.com\u0026notify_url=https%3A%2F%2Fcbpay2.9127pay.com%2Fdiaodepibao%2Fchannel_response%2Falipay%2Fboweilepay%2Fboweile_af\u0026sign=3021356a1adc3d7b278158715975c3b9\u0026extra=DA2018051117541419432606243212')
    # r = requests.get('http://api.91518lm.com/order/order_add?mch=282861854966\u0026pay_type=aliwap\u0026money=2000\u0026time=1526032066\u0026order_id=DA2018051117474683045606241744\u0026return_url=http://www.baidu.com\u0026notify_url=https://cbpay2.9127pay.com/diaodepibao/channel_response/alipay/qianjinwappay/ali_changjiang\u0026create_ip=119.23.110.27\u0026sign=db1489de4c668a6ab3adb6a87812aba7')
    print r.text
    print r.url
